package com.eemint.service;

import com.eemint.entity.MailInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.*;

/****
 *  Copyright (C), 2019,12, szcport
 *  File name and path : com.eemint.service.MailService.java
 *  Author : Dallas,
 *  Version : 1.0,
 *  First complete date : 2019/12/24 14:37
 *  Description : mail 服务类
 *  History:  nothing
 *
 ***/
@Slf4j
@Service
public class MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${mail.sender}")
    private String SENDER = "306151423@qq.com";

    @Value("${mail.receiver}")
    private String RECEIVER = "wangtao932@aliyun.com";

    //队列大小
    private final int QUEUE_LENGTH = 10000;
    //基于内存的阻塞队列
    private BlockingQueue<MailInfo> queue = new LinkedBlockingQueue<MailInfo>(QUEUE_LENGTH);
    //创建计划任务执行器
    private ScheduledExecutorService es = Executors.newScheduledThreadPool(1);


    public MailService() {
        execute();
    }

    /**
     * 添加信息至队列中
     *
     * @param invo
     */
    public void addQueue(MailInfo invo) {
        queue.add(invo);
    }

    /**
     * 初始化执行
     */
    public void execute() {
        //每一分钟执行一次
        es.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                MailInfo invo = null;
                try {
                    invo = queue.take();
                    //处理队列中的信息。。。。。
                    sendSimpleMailMessge(invo);
                    log.info("发送成功>>>>[{}, {}, {}]", invo.getNick(), invo.getMail(), invo.getRemark());
                } catch (InterruptedException e) {
                    if (invo != null) {
                        log.info("发送失败>>>>[{}, {}, {}]", invo.getNick(), invo.getMail(), invo.getRemark());
                    }
                    log.error("邮件发送异常", e);
                }
            }

        }, 0, 1, TimeUnit.MINUTES);
    }

    /**
     * 发送普通邮件
     *
     * @param invo
     */
    public void sendSimpleMailMessge(MailInfo invo) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(SENDER);//发件人
        message.setTo(RECEIVER);//接收人
        message.setSubject("收到 " + invo.getNick() + " 消息");//主题
        String str = "昵称: %s \n邮箱: %s \n内容: %s";
        String content = String.format(str, invo.getNick(), invo.getMail(), invo.getRemark());
        message.setText(content);//内容
        try {
            mailSender.send(message);
        } catch (Exception e) {
            log.error("发送简单邮件时发生异常!", e);
        }
    }

}
